module Confit
  class Confit < ActiveRecord::Base
    self.table_name = :confits

    attr_accessible :description, :name, :value
    after_save :invalidate_cache

    def self.get(name, default = nil, description = nil)
      obj = _get(name, default, description)
      if obj.bool?
        result = obj.value.to_i == 1 
      elsif obj.choose?
        result = obj.value.split('|').map{|s| s.strip }
      else
        result = obj.value
      end
      result
    end

    def self.set(name, default = nil, description = nil)
      obj = self.obj(name, default, description)
      if obj.value.to_s != default.to_s
        obj.value = default
        obj.save
      end
      obj.value
    end

    def self.obj(name, default = nil, description = nil)
      _get(name, default, description)
    end

    def ckeditor?
      name=~/^doc_(.*?)$/
    end

    def bool?
      name=~/^bool_(.*?)$/
    end

    def choose?
      name=~/^choose_(.*?)$/
    end
    

    def self.invalidate_cache
      @application_settings = nil
    end

    private 

    def self.get_all
      @application_settings = {}
      all.each {|i| @application_settings[i.name] = i }
      @application_settings
    end

    def self._get(name, default = nil, description = nil)
      @application_settings ||= get_all
      if !@application_settings.key?(name) 
        self._set(name, default, description)
        get_all
      end
      @application_settings[name]
    end

    def self._set(name, default = nil, description = nil)
      default = (default == 1 || default == true ? 1 : 0) if name=~/^bool_(.*?)$/
      if name=~/^choose_(.*?)$/
        default = default.join('|') if  default.is_a? Array 
        default = default.values.join('|') if  default.is_a? Hash
      end

      Confit.create(:name => name, :value => default, :description => description.nil? ? name : description)
    end

    def invalidate_cache
      Confit.invalidate_cache
    end
  end
end